'use client'

import { useState, useEffect, useMemo } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import { ChevronRightIcon } from 'lucide-react'

// 专业定义
const SPECIALTIES = [
  { code: 'piping', name: '配管专业', subSpecialties: [
    { code: 'drainage', name: '给排水' },
    { code: 'fire', name: '消防' },
    { code: 'process', name: '工艺' },
    { code: 'piping', name: '配管' }
  ]},
  { code: 'electrical', name: '电气专业' },
  { code: 'hvac', name: '暖通专业' },
  { code: 'communication', name: '通信专业' },
  { code: 'instrumentation', name: '仪表专业' }
]

interface DeviceTypeMapping {
  device_id: string;
  classification_code: string;
  classification_name: string;
  specialty: string;
  sub_specialty?: string;
  name: string;
}

interface ObjectCategory {
  name: string;
  count: number;
  deviceTypes: DeviceTypeMapping[];
}

interface SimpleDeviceSelectorProps {
  selectedSpecialty?: string;
  selectedSubSpecialty?: string;
  selectedObjectCategory?: string;
  selectedDeviceType?: string;
  onSpecialtyChange?: (specialty: string) => void;
  onSubSpecialtyChange?: (subSpecialty: string) => void;
  onObjectCategoryChange?: (category: string) => void;
  onDeviceTypeChange?: (deviceType: string) => void;
  hideDeviceTypeSelection?: boolean;
  className?: string;
}

export function SimpleDeviceSelector({
  selectedSpecialty,
  selectedSubSpecialty,
  selectedObjectCategory,
  selectedDeviceType,
  onSpecialtyChange,
  onSubSpecialtyChange,
  onObjectCategoryChange,
  onDeviceTypeChange,
  hideDeviceTypeSelection = false,
  className
}: SimpleDeviceSelectorProps) {
  const [deviceTypes, setDeviceTypes] = useState<DeviceTypeMapping[]>([]);
  const [objectCategories, setObjectCategories] = useState<ObjectCategory[]>([]);
  const [loading, setLoading] = useState(false);

  // 加载所有设备类型（使用设备实例数据以保持与专业导航一致）
  const loadDeviceTypes = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/device-hierarchy-by-name');
      const data = await response.json();
      if (data.success) {
        // 将层次结构数据转换为设备类型数组
        const allDevices = data.data.flatMap((hierarchy: any) => 
          hierarchy.devices.map((device: any) => ({
            device_id: device.device_id,
            classification_code: device.classification_code,
            classification_name: device.classification_name,
            specialty: device.specialty,
            sub_specialty: device.sub_specialty,
            name: device.name
          }))
        );
        setDeviceTypes(allDevices);
        generateObjectCategories(allDevices);
        
        console.log('加载的设备类型数据:', {
          totalDevices: allDevices.length,
          sampleDevices: allDevices.slice(0, 3),
          specialties: [...new Set(allDevices.map(d => d.specialty))],
          categories: [...new Set(allDevices.map(d => d.classification_name))]
        });
      }
    } catch (error) {
      console.error('加载设备类型失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 生成对象分类列表
  const generateObjectCategories = (allDeviceTypes: DeviceTypeMapping[]) => {
    const categoryMap = new Map<string, DeviceTypeMapping[]>();
    
    allDeviceTypes.forEach(deviceType => {
      if (!categoryMap.has(deviceType.classification_name)) {
        categoryMap.set(deviceType.classification_name, []);
      }
      categoryMap.get(deviceType.classification_name)!.push(deviceType);
    });

    const categories: ObjectCategory[] = Array.from(categoryMap.entries()).map(([name, types]) => ({
      name,
      count: types.length,
      deviceTypes: types
    }));

    setObjectCategories(categories);
  };

  // 根据专业和子专业筛选对象分类
  const filteredObjectCategories = useMemo(() => {
    if (!selectedSpecialty || objectCategories.length === 0) return [];
    
    // 将英文代码转换为中文名称进行过滤
    const specialtyName = SPECIALTIES.find(s => s.code === selectedSpecialty)?.name;
    if (!specialtyName) return [];
    
    return objectCategories
      .map(category => {
        let filteredDeviceTypes = category.deviceTypes.filter(dt => dt.specialty === specialtyName);
        
        // 如果选择了配管专业的子专业，进一步过滤
        if (selectedSpecialty === 'piping' && selectedSubSpecialty) {
          const subSpecialtyName = SPECIALTIES.find(s => s.code === selectedSpecialty)?.subSpecialties?.find(sub => sub.code === selectedSubSpecialty)?.name;
          if (subSpecialtyName) {
            filteredDeviceTypes = filteredDeviceTypes.filter(dt => dt.sub_specialty === subSpecialtyName);
          }
        }
        
        return {
          ...category,
          deviceTypes: filteredDeviceTypes,
          count: filteredDeviceTypes.length
        };
      })
      .filter(category => category.count > 0);
  }, [selectedSpecialty, selectedSubSpecialty, objectCategories]);

  // 根据对象分类筛选设备分类
  const filteredDeviceTypes = useMemo(() => {
    if (!selectedObjectCategory) return [];
    
    const category = filteredObjectCategories.find(cat => cat.name === selectedObjectCategory);
    return category ? category.deviceTypes : [];
  }, [selectedObjectCategory, filteredObjectCategories]);

  // 处理专业选择
  const handleSpecialtyChange = (specialty: string) => {
    onSpecialtyChange?.(specialty);
    onSubSpecialtyChange?.('');
    onObjectCategoryChange?.('');
    onDeviceTypeChange?.('');
  };

  // 处理子专业选择
  const handleSubSpecialtyChange = (subSpecialty: string) => {
    onSubSpecialtyChange?.(subSpecialty);
    onObjectCategoryChange?.('');
    onDeviceTypeChange?.('');
  };

  // 处理对象分类选择
  const handleObjectCategoryChange = (category: string) => {
    onObjectCategoryChange?.(category);
    onDeviceTypeChange?.('');
  };

  useEffect(() => {
    loadDeviceTypes();
  }, []);

  return (
    <Card className={className}>
      <CardHeader className="pb-4">
        <CardTitle className="text-lg">设备选择</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 选择流程指示 */}
        <div className="flex items-center gap-2 text-sm text-gray-500 mb-6">
          <span className={selectedSpecialty ? "text-blue-600 font-medium" : ""}>专业</span>
          {selectedSpecialty === 'piping' && (
            <>
              <ChevronRightIcon className="w-3 h-3" />
              <span className={selectedSubSpecialty ? "text-blue-600 font-medium" : ""}>子专业</span>
            </>
          )}
          <ChevronRightIcon className="w-3 h-3" />
          <span className={selectedObjectCategory ? "text-blue-600 font-medium" : ""}>对象分类</span>
          {!hideDeviceTypeSelection && (
            <>
              <ChevronRightIcon className="w-3 h-3" />
              <span className={selectedDeviceType ? "text-blue-600 font-medium" : ""}>设备分类</span>
            </>
          )}
        </div>

        {/* 专业选择 */}
        <div className="space-y-2">
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-gray-700">1. 专业</span>
            {selectedSpecialty && (
              <Badge variant="secondary" className="text-xs">
                {SPECIALTIES.find(s => s.code === selectedSpecialty)?.name}
              </Badge>
            )}
          </div>
          <Select value={selectedSpecialty || ''} onValueChange={handleSpecialtyChange}>
            <SelectTrigger>
              <SelectValue placeholder="选择专业" />
            </SelectTrigger>
            <SelectContent>
              {SPECIALTIES.map(specialty => (
                <SelectItem key={specialty.code} value={specialty.code}>
                  {specialty.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* 配管专业子专业选择 */}
        {selectedSpecialty === 'piping' && (
          <div className="space-y-2">
            <div className="flex items-center gap-2">
              <span className="text-sm font-medium text-gray-700">2. 子专业</span>
              {selectedSubSpecialty && (
                <Badge variant="secondary" className="text-xs">
                  {SPECIALTIES.find(s => s.code === selectedSpecialty)?.subSpecialties?.find(sub => sub.code === selectedSubSpecialty)?.name}
                </Badge>
              )}
            </div>
            <Select value={selectedSubSpecialty || ''} onValueChange={handleSubSpecialtyChange}>
              <SelectTrigger>
                <SelectValue placeholder="选择子专业" />
              </SelectTrigger>
              <SelectContent>
                {SPECIALTIES.find(s => s.code === selectedSpecialty)?.subSpecialties?.map(subSpecialty => (
                  <SelectItem key={subSpecialty.code} value={subSpecialty.code}>
                    {subSpecialty.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        )}

        {/* 对象分类选择 */}
        {selectedSpecialty && (selectedSpecialty !== 'piping' || selectedSubSpecialty) && (
          <div className="space-y-2">
            <div className="flex items-center gap-2">
              <span className="text-sm font-medium text-gray-700">{selectedSpecialty === 'piping' ? '3.' : '2.'} 对象分类</span>
              {selectedObjectCategory && (
                <Badge variant="secondary" className="text-xs">
                  {selectedObjectCategory}
                </Badge>
              )}
              <span className="text-xs text-gray-400">
                ({filteredObjectCategories.length}类可选)
              </span>
            </div>
            <Select 
              value={selectedObjectCategory || ''} 
              onValueChange={handleObjectCategoryChange}
              disabled={loading || filteredObjectCategories.length === 0}
            >
              <SelectTrigger>
                <SelectValue placeholder="选择对象分类" />
              </SelectTrigger>
              <SelectContent>
                {filteredObjectCategories.map(category => (
                  <SelectItem key={category.name} value={category.name}>
                    <div className="flex items-center justify-between w-full">
                      <span>{category.name}</span>
                      <Badge variant="outline" className="ml-2 text-xs">
                        {category.count}
                      </Badge>
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        )}

        {/* 设备分类选择 */}
        {!hideDeviceTypeSelection && selectedObjectCategory && filteredDeviceTypes.length > 0 && (
          <div className="space-y-2">
            <div className="flex items-center gap-2">
              <span className="text-sm font-medium text-gray-700">{selectedSpecialty === 'piping' ? '4.' : '3.'} 设备分类</span>
              {selectedDeviceType && (
                <Badge variant="secondary" className="text-xs">
                  {filteredDeviceTypes.find(dt => dt.device_id === selectedDeviceType)?.name}
                </Badge>
              )}
              <span className="text-xs text-gray-400">
                ({filteredDeviceTypes.length}个可选)
              </span>
            </div>
            <Select 
              value={selectedDeviceType || ''} 
              onValueChange={onDeviceTypeChange}
              disabled={loading}
            >
              <SelectTrigger>
                <SelectValue placeholder="选择设备分类" />
              </SelectTrigger>
              <SelectContent>
                {filteredDeviceTypes.map(deviceType => (
                  <SelectItem key={deviceType.device_id} value={deviceType.device_id}>
                    {deviceType.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        )}

        {/* 完成选择提示 */}
        {selectedDeviceType && (
          <div className="mt-4 p-3 bg-green-50 rounded-lg border border-green-200">
            <div className="text-sm text-green-800">
              ✓ 已选择设备分类，可进行模板操作
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}